<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(B卷,200分)- 树状结构查询（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>通常使用多行的节点、父节点表示一棵树&#xff0c;比如</p> 
<p>西安 陕西<br /> 陕西 中国<br /> 江西 中国<br /> 中国 亚洲<br /> 泰国 亚洲</p> 
<p>输入一个节点之后&#xff0c;请打印出来树中他的所有下层节点</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入行数&#xff0c;下面是多行数据&#xff0c;每行以空格区分节点和父节点</p> 
<p>接着是查询节点</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出查询节点的所有下层节点。以字典序排序</p> 
<p></p> 
<h4>备注</h4> 
<p>树中的节点是唯一的&#xff0c;不会出现两个节点&#xff0c;是同一个名字</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">5<br /> b a<br /> c a<br /> d c<br /> e c<br /> f d<br /> c</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">d<br /> e<br /> f</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>用例图示如下</p> 
<p><img alt="" height="289" src="https://img-blog.csdnimg.cn/5c7e40b633b141028424631fc3902c65.png" width="334" /></p> 
<p>需要打印c下面的所有子节点&#xff0c;即d,e,f节点&#xff0c;按照字典序输出后是d,e,f。 </p> 
<p></p> 
<p>本题其实就是让我们遍历树结构&#xff0c;可以使用深搜或者广搜。下面代码使用广搜。</p> 
<p>关于本题树结构&#xff0c;可以使用Map结构实现&#xff0c;即key为父节点&#xff0c;value为子节点集合。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61; 1) {
    n &#61; parseInt(lines[0]);
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 2) {
    lines.shift();

    const target &#61; lines.pop();

    const tree &#61; {};
    for (let str of lines) {
      const [ch, fa] &#61; str.split(&#34; &#34;);
      if (!tree[fa]) tree[fa] &#61; new Set();
      tree[fa].add(ch);
    }

    getResult(tree, target);

    lines.length &#61; 0;
  }
});

function getResult(tree, target) {
  if (!tree[target]) return console.log(&#34;&#34;);

  const queue &#61; [...tree[target]];

  const ans &#61; [];
  while (queue.length &gt; 0) {
    const node &#61; queue.shift();
    ans.push(node);

    if (tree[node]) {
      queue.push(...tree[node]);
    }
  }

  ans.sort().forEach((v) &#61;&gt; console.log(v));
}
</code></pre> 
<p> </p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    HashMap&lt;String, HashSet&lt;String&gt;&gt; tree &#61; new HashMap&lt;&gt;();
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      String ch &#61; sc.next();
      String fa &#61; sc.next();

      tree.putIfAbsent(fa, new HashSet&lt;&gt;());
      tree.get(fa).add(ch);
    }

    String target &#61; sc.next();

    getResult(tree, target);
  }

  public static void getResult(HashMap&lt;String, HashSet&lt;String&gt;&gt; tree, String target) {
    if (!tree.containsKey(target)) {
      System.out.println(&#34;&#34;);
      return;
    }

    LinkedList&lt;String&gt; queue &#61; new LinkedList&lt;&gt;(tree.get(target));

    ArrayList&lt;String&gt; ans &#61; new ArrayList&lt;&gt;();

    while (queue.size() &gt; 0) {
      String node &#61; queue.removeFirst();
      ans.add(node);

      if (tree.containsKey(node)) queue.addAll(tree.get(node));
    }

    ans.sort(String::compareTo);

    ans.forEach(System.out::println);
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())

tree &#61; {}
for _ in range(n):
    ch, fa &#61; input().split()
    tree.setdefault(fa, set())
    tree[fa].add(ch)

target &#61; input()


# 算法入口
def getResult():
    if tree.get(target) is None:
        print(&#34;&#34;)
        return

    queue &#61; list(tree[target])
    ans &#61; []

    while len(queue) &gt; 0:
        node &#61; queue.pop(0)
        ans.append(node)

        if tree.get(node) is not None:
            queue.extend(list(tree[node]))

    ans.sort()
    for v in ans:
        print(v)


# 算法调用
getResult()
</code></pre> 
<p></p>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>